package com.ultrapower.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.scan.Traced;
import com.ultrapower.commons.shiro.ShiroUser;
import com.ultrapower.commons.utils.JsonUtils;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.commons.utils.TestGis;
import com.ultrapower.model.Enterprise;
import com.ultrapower.model.EnterpriseOnline;
import com.ultrapower.model.NetgridModel;
import com.ultrapower.model.OrderModel;
import com.ultrapower.model.Organization;
import com.ultrapower.model.User;
import com.ultrapower.service.IMapOnlineService;
import com.ultrapower.service.IMapService;
import com.ultrapower.service.IOrganizationService;
import com.ultrapower.service.IProductService;
import com.ultrapower.service.IUserService;

/**
 * @description：基础地图
 * @author：polly
 * @date：2018-6-4 16:06:55
 */
@Controller
@RequestMapping("/map")
public class MapController extends BaseController{

	@Autowired
    private IMapService mapService;
	@Autowired
    private IMapOnlineService mapOnlineService;
	@Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IProductService productService;
	
	/**
     * 展示地图企业信息
     *
     * @param Enterprise
     * @return
     */
    @PostMapping("/show")
    @ResponseBody
    public Object showMap(String province,String cityName,String industry,String develop,String type,String scale) {
    	Enterprise enterprise = new Enterprise();
    	enterprise.setProvince(province);
    	enterprise.setCityName(cityName);
    	enterprise.setIndustry(industry);
    	enterprise.setDevelop(develop);
    	enterprise.setType(type);
    	enterprise.setScale(scale);
        List<Enterprise> list = mapService.selectByInd(enterprise);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
        	Enterprise ent = list.get(i);
        	if(ent.getLongitude() != null){
        		JSONObject json = new JSONObject();
        		JSONObject geometry = new JSONObject();
        		json.put("id", ent.getId());
        		geometry.put("type", "Point");
        		//float[] x={Float.parseFloat(ent.getLongitude()),Float.parseFloat(ent.getLatitude())};
        		float[] x={Float.parseFloat(ent.getLongitude()),Float.parseFloat(ent.getLatitude())};
        		String develops = ent.getDevelop();
        		geometry.put("coordinates", x);
        		json.put("geometry", geometry);
        		//已发展
        		if("1".equals(develops)){
        			json.put("count", 1);
        		//未发展
        		}else if("2".equals(develops)){
        			json.put("count", 2);
        		}
//        		json.put("lng", Float.parseFloat(ent.getLongitude()));
//        		json.put("lat", Float.parseFloat(ent.getLatitude()));
        		jsonArray.put(json);
        	}
		}
//        String result = JsonUtils.toJson(list);
        return jsonArray.toString();
    }
    
    /**
     * 按名称搜索地图企业信息
     *
     * @param Enterprise
     * @return
     */
    @PostMapping("/showByName")
    @ResponseBody
    public Object showMapByName(String companyName) {
    	Enterprise enterprise = new Enterprise();
    	enterprise.setCompanyName(companyName);
        List<Enterprise> list = mapService.selectByName(enterprise);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
        	Enterprise ent = list.get(i);
        	if(ent.getLongitude() != null){
        		JSONObject json = new JSONObject();
        		JSONObject geometry = new JSONObject();
        		json.put("id", ent.getId());
        		geometry.put("type", "Point");
        		String[] x={ent.getLongitude(),ent.getLatitude()};
        		String develop = ent.getDevelop();
        		geometry.put("coordinates", x);
        		json.put("geometry", geometry);
        		//已发展
        		if("1".equals(develop)){
        			json.put("count", 1);
        		//未发展
        		}else if("2".equals(develop)){
        			json.put("count", 2);
        		}
        		jsonArray.put(json);
        	}
		}
        return jsonArray.toString();
    }
    
    /**
     * 展示单个企业详细信息
     *
     * @param Enterprise
     * @return
     */
    @GetMapping("/infoWindow")
    @ResponseBody
    public Object showInfoWindow(int id) {
    	Enterprise enterprise = mapService.selectById(id);
        String result = JsonUtils.toJson(enterprise);
        return result;
    }
    
    /**
     * 企业报表页
     *
     * @return
     */
    @GetMapping("/showGrid")
    public String showGrid() {
        return "admin/data/grid";
    }
    
    /**
     * 编辑企业列表页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editGrid")
    public String editGrid(Model model, int id) {
    	Enterprise enterprise = mapService.selectById(id);
        model.addAttribute("grid", enterprise);
        return "admin/data/editGrid";
    }
    
    /**
     * 编辑企业列表页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editGridOnline")
    public String editGridOnline(Model model, int id) {
    	EnterpriseOnline enterpriseOnline = mapOnlineService.selectById(id);
        model.addAttribute("grid", enterpriseOnline);
        return "admin/data/editGrid";
    }
    
    /**
     * 编辑企业
     *
     * @param userVo
     * @return
     */
    @Traced(name="编辑企业信息")
//  @RequiresRoles("admin")
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@Valid Enterprise enterprise) {
    	mapService.updateByVo(enterprise);
        return renderSuccess("修改成功！");
    }
    
    /**
     * 编辑企业
     *
     * @param userVo
     * @return
     */
    @Traced(name="编辑导入企业信息")
    @RequiresRoles("admin")
    @PostMapping("/editOnline")
    @ResponseBody
    public Object editOnline(@Valid EnterpriseOnline enterpriseOnline) {
    	mapOnlineService.updateByVo(enterpriseOnline);
        return renderSuccess("修改成功！");
    }
    
    /**
     * 企业列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(Enterprise enterprise, Integer page, Integer limit, String sort, String order,String cityName,String industry,String companyName,String develop,String type,String scale) {
    	sort = "id";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        String province = enterprise.getProvince();
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    	User user = userService.selectById(shiroUser.getId());
    	Organization oi = organizationService.selectById(user.getOrganizationId());
    	if(StringUtils.isNotBlank(oi.getProvince())){
    		if(StringUtils.isNotBlank(province)){
    			if(province.equals(oi.getProvince())){
    				condition.put("province", oi.getProvince());
    			}else{
    				return pageInfo;
    			}
    		}else{
    			condition.put("province", oi.getProvince());
    		}
    	}
    	if(StringUtils.isNotBlank(oi.getCity())){
    		if(StringUtils.isNotBlank(cityName)){
    			if(cityName.equals(oi.getCity())){
    				condition.put("cityName", oi.getCity());
    			}else if(shiroUser.getRoles().contains("admin")){
    				condition.put("cityName", cityName);
    			}else{
    				return pageInfo;
    			}
    		}else if(shiroUser.getRoles().contains("admin")){
    			
    		}else{
    			condition.put("cityName", oi.getCity());
    		}
    	}
//        if (StringUtils.isNotBlank(province) && province.equals(oi.getProvince())) {
//        	condition.put("province", province);
//        }
//        if (StringUtils.isNotBlank(cityName) && cityName.equals(oi.getCity())) {
//            condition.put("cityName", cityName);
//        }
//    	if("".equals(cityName)){
//    		condition.put("cityName", oi.getCity());
//    	}
        if (StringUtils.isNotBlank(industry)) {
            condition.put("industry", industry);
        }
        if (StringUtils.isNotBlank(develop) && !"0".equals(develop)) {
            condition.put("develop", develop);
        }
        if (StringUtils.isNotBlank(companyName)) {
            condition.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(industry)) {
            condition.put("industry", industry);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(scale)) {
            condition.put("scale", scale);
        }
        pageInfo.setCondition(condition);
        mapService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * 计算圆内数据
     *
     * @param Enterprise
     * @return
     */
    @PostMapping("/countDistance")
    @ResponseBody
    public Object countDistance(String province,String cityName,String industry,String develop,String type,String scale,String longitude,String latitude,String radius) {
    	Enterprise enterprise = new Enterprise();
    	enterprise.setProvince(province);
    	enterprise.setCityName(cityName);
    	enterprise.setIndustry(industry);
    	enterprise.setDevelop(develop);
    	enterprise.setType(type);
    	enterprise.setScale(scale);
    	enterprise.setLongitude(longitude);
    	enterprise.setLatitude(latitude);
    	enterprise.setWebsite(radius);
        List<Enterprise> list = mapService.selectcountDistance(enterprise);
        Object jsonpro = productService.selectTreeGrid();
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = null;
        if(!shiroUser.getRoles().contains("admin")) {
        	user = userService.selectById(getUserId());
        }
        Object jsonuser = userService.selectTreeGrid(user);
        JSONObject jsonRes = new JSONObject();
        JSONObject jsonMsg = new JSONObject();
        int countisdevelop = 0;
        int countnodevelop = 0;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
        	Enterprise ent = list.get(i);
        	if(ent.getLongitude() != null){
        		JSONObject json = new JSONObject();
        		JSONObject geometry = new JSONObject();
        		String develops = ent.getDevelop();
        		json.put("id", ent.getId());
        		geometry.put("type", "Point");
        		float[] x={Float.parseFloat(ent.getLongitude()),Float.parseFloat(ent.getLatitude())};
        		//String[] x={ent.getLongitude(),ent.getLatitude()};
        		geometry.put("coordinates", x);
        		json.put("geometry", geometry);
        		//已发展
        		if("1".equals(develops)){
        			countisdevelop++;
        			json.put("count", 1);
        		//未发展
        		}else if("2".equals(develops)){
        			countnodevelop++;
        			json.put("count", 2);
        		}
        		jsonMsg.put("isdevelop", countisdevelop);
        		jsonMsg.put("nodevelop", countnodevelop);
        		jsonArray.put(json);
        		jsonRes.put("data", jsonArray);
        		jsonRes.put("msg", jsonMsg);
        		jsonRes.put("product", jsonpro);
        		jsonRes.put("user", jsonuser);
        	}
		}
        return jsonRes.toString();
    }
    
    /**
     * 计算任意多边形内数据
     *
     * @param Enterprise
     * @return
     */
    @PostMapping("/countPolygon")
    @ResponseBody
    public Object countPolygon(String province,String cityName,String industry,String develop,String type,String scale,String data) {
    	String appJson = StringEscapeUtils.unescapeHtml(data);//appJson
    	JSONArray jArray=new JSONArray(appJson); //将传过来的json字符串放入json集合，
    	List<NetgridModel> nlist = new ArrayList<NetgridModel>();
    	for (int i = 0; i < jArray.length(); i++) {
			JSONObject jsonObj = jArray.getJSONObject(i);
			double longitude = jsonObj.getDouble("lng");
			double latitude = jsonObj.getDouble("lat");
			NetgridModel nm = new NetgridModel();
			nm.setLonX(longitude);
			nm.setLatY(latitude);
			nlist.add(i,nm);
		}
    	Enterprise enterprise = new Enterprise();
    	enterprise.setProvince(province);
    	enterprise.setCityName(cityName);
    	enterprise.setIndustry(industry);
    	enterprise.setDevelop(develop);
    	enterprise.setType(type);
    	enterprise.setScale(scale);
        List<Enterprise> list = mapService.selectcountPolygon(enterprise);
        Object jsonpro = productService.selectTreeGrid();
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = null;
        if(!shiroUser.getRoles().contains("admin")) {
        	user = userService.selectById(getUserId());
        }
        Object jsonuser = userService.selectTreeGrid(user);
        JSONObject jsonRes = new JSONObject();
        JSONObject jsonMsg = new JSONObject();
        int countisdevelop = 0;
        int countnodevelop = 0;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
        	Enterprise ent = list.get(i);
        	if(ent.getLongitude() != null){
        		OrderModel order=new OrderModel();
        		order.setLocationX(ent.getLongitude());
        		order.setLocationY(ent.getLatitude());
        		boolean flag = TestGis.isInPolygon(order, nlist);
        		if(flag){
        			JSONObject json = new JSONObject();
            		JSONObject geometry = new JSONObject();
            		String develops = ent.getDevelop();
            		json.put("id", ent.getId());
            		geometry.put("type", "Point");
            		float[] x={Float.parseFloat(ent.getLongitude()),Float.parseFloat(ent.getLatitude())};
            		//String[] x={ent.getLongitude(),ent.getLatitude()};
            		geometry.put("coordinates", x);
            		json.put("geometry", geometry);
            		//已发展
            		if("1".equals(develops)){
            			countisdevelop++;
            			json.put("count", 1);
            		//未发展
            		}else if("2".equals(develops)){
            			countnodevelop++;
            			json.put("count", 2);
            		}
            		jsonMsg.put("isdevelop", countisdevelop);
            		jsonMsg.put("nodevelop", countnodevelop);
            		jsonArray.put(json);
            		jsonRes.put("data", jsonArray);
            		jsonRes.put("msg", jsonMsg);
            		jsonRes.put("product", jsonpro);
            		jsonRes.put("user", jsonuser);
        		}
        	}
		}
        return jsonRes.toString();
    }
    
    /**
     * 首页
     *
     * @return
     */
    @GetMapping("/main")
    public String main() {
        return "main";
    }
    
    /**
	 * 
	* @Title: showEchartCity 
	* @Description: 获取饼状图
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @author polly
	* @date 2018-6-15 11:02:40
	* @throws
	 */
    @GetMapping("/showEchartCity")
    @ResponseBody
	public String showEchartAttack(){
		List<Enterprise> list = mapService.showEchartCity();
		JSONArray json = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject jbObject=new JSONObject();
			Enterprise enterprise = list.get(i);
			jbObject.put("value", enterprise.getId());
			jbObject.put("name", enterprise.getCityName());
			json.put(jbObject);
		}
		return json.toString();
	}
    
    /**
	 * 
	* @Title: showEchartEnterprise 
	* @Description: 获取饼状图
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @author polly
	* @date 2018-6-15 11:02:40
	* @throws
	 */
    @GetMapping("/showEchartEnterprise")
    @ResponseBody
	public String showEchartEnterprise(){
		List<Enterprise> list = mapService.showEchartEnterprise();
		JSONArray json = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject jbObject=new JSONObject();
			Enterprise enterprise = list.get(i);
			jbObject.put("value", enterprise.getId());
			jbObject.put("name", enterprise.getIndustry());
			json.put(jbObject);
		}
		return json.toString();
	}
    
    /**
	 * 
	* @Title: showBarCity
	* @Description: 获取柱状图
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @author polly
	* @date 2018-9-3 10:47:19
	* @throws
	 */
    @GetMapping("/showBarCity")
    @ResponseBody
	public String showBarCity(){
		List<Enterprise> list = mapService.showBarCity();
		JSONArray json = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject jbObject=new JSONObject();
			Enterprise enterprise = list.get(i);
			jbObject.put("value", enterprise.getId());
			jbObject.put("name", enterprise.getCityName());
			json.put(jbObject);
		}
		return json.toString();
	}
    
    /**
	 * 
	* @Title: showBarEnterprise 
	* @Description: 获取柱状图
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @author polly
	* @date 2018-9-3 11:25:28
	* @throws
	 */
    @GetMapping("/showBarEnterprise")
    @ResponseBody
	public String showBarEnterprise(){
		List<Enterprise> list = mapService.showBarEnterprise();
		JSONArray json = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject jbObject=new JSONObject();
			Enterprise enterprise = list.get(i);
			jbObject.put("value", enterprise.getId());
			jbObject.put("name", enterprise.getIndustry());
			json.put(jbObject);
		}
		return json.toString();
	}
    
    @Traced(name="上传图片")
    @PostMapping("/logoUpload")
    @ResponseBody
    public String logoUpload(HttpServletRequest request,MultipartFile file){
    	JSONObject json = new JSONObject();
    	JSONObject jsonData = new JSONObject();
        try {
        	//文件上传路径
        	request.setCharacterEncoding("UTF-8");
            String path = request.getServletContext().getRealPath("/");
			String filename = file.getOriginalFilename();
			System.out.println(path+filename);
			//写入本地磁盘
			InputStream is = file.getInputStream();
			byte[] bs = new byte[1024];
			int len;
//			path = request.getSession().getServletContext().getRealPath("images"); //获取服务器指定文件存取路径
			path = "/home/enterprise/file/images/";
//			path = path+"images";
			File tmpfile = new File(path);
			if(!tmpfile.exists()){
				tmpfile.mkdir();
			}
			OutputStream os = new FileOutputStream(new File(path,filename));
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
	    	json.put("code", 0);
	    	json.put("msg", "");
	    	jsonData.put("src", filename);
	    	json.put("data", jsonData);
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
    }
    
    /**
	 * 
	* @Title: getImg 
	* @Description: 获取图片
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @author polly
	* @date 2018-10-6 21:25:08
	* @throws
	 */
    @GetMapping("/getImg")
    @ResponseBody
	public String getImg(String picture){
		JSONArray json = new JSONArray();
		JSONObject jsonres = new JSONObject();
		JSONObject jbObject = new JSONObject();
		jsonres.put("title", "企业图片");
		jsonres.put("id", "Images");
		jsonres.put("start", 0);
		jbObject.put("src", picture);
		jbObject.put("thumb", picture);
		jbObject.put("alt", "详细图片");
		jbObject.put("pid", "1");
		json.put(jbObject);
		jsonres.put("data", json);
		return jsonres.toString();
	}
}
